﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
using BlueDot.Data.Core;
using BlueDot.Data.Core.Sql;

namespace Syncronization.Strategy
{
    public class SyncServiceStrategy : StrategyBase
    {
        #region Fields

        private string baseTriggerText =
            @"CREATE TRIGGER [dbo].[{0}_DeletionTrigger] 
    ON [dbo].[{0}] 
    AFTER DELETE 
AS 
SET NOCOUNT ON 
UPDATE [dbo].[{0}_Tombstone] 
    SET [DeletionDate] = GETUTCDATE() 
    FROM deleted 
    WHERE deleted.[{1}] = [dbo].[{0}_Tombstone].[{1}] 
IF @@ROWCOUNT = 0 
BEGIN 
    INSERT INTO [dbo].[{0}_Tombstone] 
    ([{1}], DeletionDate)
    SELECT [{1}], GETUTCDATE()
    FROM deleted 
END ";

        #endregion

        #region Properties

        public bool CreateTableSchema { get; set; }
        public Type SyncBaseType { get; set; }

        #endregion

        #region public

        public override List<ICommand> BuildSchemaBuilderCommand(ISchemaBuilder schemaBuilder)
        {
            List<ICommand> commands;

            if (CreateTableSchema)
                commands = base.BuildSchemaBuilderCommand(schemaBuilder);
            else
                commands = new List<ICommand>();

            var entityBuilder = schemaBuilder as EntityBuilder;

            if (entityBuilder != null && entityBuilder.BaseEntityType == SyncBaseType)
            {
                string triggerText = CreateTriggerText(entityBuilder);

                var triggerCommand = new SqlSchemaCommand<SqlCommand>(
                    string.Format("{0}_DeleteTrigger", schemaBuilder.Name), triggerText);

                commands.Add(triggerCommand);
            }

            return commands;
        }

        #endregion

        #region private

        private string CreateTriggerText(EntityBuilder entityBuilder)
        {
            var stringBuilder = new StringBuilder();

            if (entityBuilder.UniqueKeyColumns.Count.Equals(1))
            {
                stringBuilder.AppendFormat(baseTriggerText,
                                           entityBuilder.Name, entityBuilder.UniqueKeyColumns[0].Name);
            }

            return stringBuilder.ToString();
        }

        #endregion
    }
}